package com.idc.resource.controller;

import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import com.idc.resource.model.LoginReqDto;
import com.idc.resource.model.UserInfoResDto;
import com.idc.resource.service.LoginService;
import com.idc.resource.util.LogUtil;
import com.idc.resource.util.Result;
import com.idc.resource.util.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 登录控制
 * Created by Lijing on 2017/7/5.
 */
@Slf4j
@RestController
@RequestMapping(value = "/login")
public class LoginController {

    /** 登录服务 */
    @Autowired
    private LoginService loginService;

    /**
     * 用户登录
     * @param loginReqDto 登录请求
     * @return 登录的用户信息
     */
    @RequestMapping(value = "/in", method = RequestMethod.POST)
    public Result<UserInfoResDto> login(@RequestBody LoginReqDto loginReqDto){
        try {
            LogUtil.updateLogId(null);
            log.info("收到一个用户登录请求，请求参数:{}",loginReqDto);
            VerifyUtil.validateObject(loginReqDto);
            return new Result<>(loginService.login(loginReqDto));
        }catch (IdcServiceException ise){
            log.error("用户登录失败，原因:{}",ise.getMessage());
            return new Result<>(ise.getCode(),ise.getMessage());
        }catch (Exception e){
            log.error("用户登录失败系统异常：",e);
            return new Result<>(ErrorCodeEnum.SYSTEM_ERROR.getCode(),ErrorCodeEnum.SYSTEM_ERROR.getDesc());
        }
    }

    /**
     * 用户登出
     * @param token 登录令牌
     * @return 登出结果
     */
    @RequestMapping(value = "/out/{token}", method = RequestMethod.POST)
    public Result<Boolean> loginOut(@PathVariable("token")String token){
        try {
            LogUtil.updateLogId(null);
            log.info("收到一个用户登出，请求参数:{}",token);
            return new Result<>(loginService.loginOut(token));
        }catch (IdcServiceException ise){
            log.error("用户登出失败，原因:{}",ise.getMessage());
            return new Result<>(ise.getCode(),ise.getMessage());
        }catch (Exception e){
            log.error("用户登出失败系统异常：",e);
            return new Result<>(ErrorCodeEnum.SYSTEM_ERROR.getCode(),ErrorCodeEnum.SYSTEM_ERROR.getDesc());
        }
    }
}
